#include "background_playfield.h"
#include <assert.h>

Background_playfield *create_bg_playfield(SDL_Surface *surf, float speed) {
  Background_playfield *playfield;

  assert(speed > 0);
  if((playfield = calloc(1, sizeof(sizeof(Background_playfield)))) == NULL) return NULL;
  playfield->playfield = surf;
  playfield->speed = speed;
  assert(playfield->pos == 0.0);
  assert(playfield->powner == 0);
  return playfield;
}

void blit_bg_playfield(const Background_playfield *playfield, SDL_Surface *surf) {
  float pos;
  SDL_Rect rect = { 0, 0, 0, 0 };

  while(rect.y < surf->h) {
    for(pos = playfield->pos; pos < surf->w; pos += playfield->playfield->w) {
      rect.x = pos;
      SDL_BlitSurface(playfield->playfield, NULL, surf, &rect);
    }
    rect.x = 0;
    rect.y += playfield->playfield->h;
  }
}

void update_bg_playfield(Background_playfield *playfield, float movementrate) {
  if((playfield->pos -= playfield->speed * movementrate) < -playfield->playfield->w) {
    playfield->pos += playfield->playfield->w;
  }
}

void free_bg_playfield(Background_playfield *playfield) {
  if(playfield->powner) SDL_FreeSurface(playfield->playfield);
  free(playfield);
}
